package org.etnaframework.module.web.api;

import org.etnaframework.module.base.utils.DbMap;
import org.etnaframework.module.base.utils.JacksonUtils;
import org.etnaframework.module.base.utils.StackTraceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Web服务器通用配置默认实现，可在业务代码中按需覆盖
 *
 * @author jasyaf
 * @since 2024-09-12
 */
public class DefaultWebCommonCustomizer implements IWebCommonCustomizer {

    public static final Logger log = LoggerFactory.getLogger(DefaultWebCommonCustomizer.class);

    @Override
    public String getRemoteAddr(HttpServletRequest request) {
        return request.getRemoteAddr();
    }

    @Override
    public String getScheme(HttpServletRequest request) {
        return request.getScheme();
    }

    @Override
    public void beforeRequest(HttpServletRequest request, HttpServletResponse response) {

    }

    @Override
    public void afterRequest(HttpServletRequest request, HttpServletResponse response) {

    }

    @Override
    public void errorPage(HttpServletRequest request, HttpServletResponse response, HttpStatus status) {
        DbMap data = new DbMap();
        data.put("method", request.getMethod());
        data.put("status", status.value());
        data.put("url", request.getRequestURI());
        write(request, response, JacksonUtils.toJson(data));
    }

    @Override
    public void error(HttpServletRequest request, HttpServletResponse response, Throwable ex) {
        DbMap data = new DbMap();
        data.put("method", request.getMethod());
        data.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
        data.put("url", request.getRequestURI());
        data.put("trace", StackTraceUtils.printThrowableSimple(ex));
        write(request, response, JacksonUtils.toJson(data));
    }

    void write(HttpServletRequest request, HttpServletResponse response, String content) {
        // 2024-01-03 虽然这里会提示APPLICATION_JSON_UTF8_VALUE过期
        // 但实测发现，在PostMan等工具中如果不用这个，中文会乱码，所以还是得保留
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        try {
            PrintWriter writer = response.getWriter();
            writer.write(null != content ? content : "");
            writer.flush();
        } catch (IOException e) {
            log.error("", e);
        }
    }
}
